package part2.task2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Consumer implements Runnable {
    private final Buffer<Object> buffer;
    private final String name;
    private final ReentrantLock lock;
    private final Condition addCondition;
    private final Condition getCondition;

    public Consumer(String name,ReentrantLock lock,Condition addCondition,Condition getCondition, Buffer<Object> buffer) {
        this.buffer = buffer;
        this.name=name;
        this.lock=lock;
        this.addCondition=addCondition;
        this.getCondition=getCondition;
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            try{
                lock.lock();
                if (buffer.isEmpty()){
                    try {
                        System.out.println("Consumer "+name+" wait.");
                        getCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("Consumer "+name+" get.");
                    buffer.get();
                    addCondition.signal();
                }
            } finally {
                lock.unlock();
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
